package com.jlastu.znb.buy;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jlastu.znb.database.DBHelper;
import com.jlastu.znb.utils.SpUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class buyManager {
    private DBHelper dbHelper;
    private Context context;
    private SpUtils mSpUtils;
    public buyManager(Context context) {
        this.context = context;
        this.dbHelper = new DBHelper(context);
        this.mSpUtils = new SpUtils(context); // 初始化SpUtils
    }
    public void addTobuy(int goodsId, int quantity, int userId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("goods_id", goodsId);
        values.put("quantity", quantity); // 初始化数量
        values.put("user_id", userId);

        // 检查购物车中是否已有该商品
        String[] columns = { "quantity" };
        String selection = "goods_id=? AND user_id=?";
        String[] selectionArgs = { String.valueOf(goodsId), String.valueOf(userId) };
        Cursor cursor = db.query("buy", columns, selection, selectionArgs, null, null, null);

        if (cursor.moveToFirst()) {
            // 如果存在，更新数量
            int currentQuantity = cursor.getInt(0);
            quantity += currentQuantity; // 增加现有数量
            values.put("quantity", quantity); // 更新ContentValues中的数量
            String whereClause = "goods_id=? AND user_id=?";
            String[] whereArgs = { String.valueOf(goodsId), String.valueOf(userId) };
            db.update("buy", values, whereClause, whereArgs);
        } else {
            // 如果不存在，插入新记录
            db.insert("buy", null, values);
        }
        cursor.close();
    }

    @SuppressLint("Range")
    public List<buyItem> getbuyItems() {
        List<buyItem> buyItems = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // SQL查询，关联商品表和购物车表
        String query = "SELECT buy.*, goods.goods_name, goods.goods_price, photo.image " +
                "FROM buy " +
                "JOIN goods ON buy.goods_id = goods._id " +
                "LEFT JOIN photo ON goods._id = photo.goods_id " +
                "WHERE buy.user_id = ?";
        String[] args = { String.valueOf(getUserId()) };
        Cursor cursor = db.rawQuery(query, args);
        if (cursor.moveToFirst()) {
            do {
                buyItem buyItem = new buyItem();
                // 填充buyItem对象
                buyItem.setId(cursor.getInt(cursor.getColumnIndex("_id")));
                buyItem.setGoodsId(cursor.getInt(cursor.getColumnIndex("goods_id")));
                buyItem.setGoodsName(cursor.getString(cursor.getColumnIndex("goods_name")));
                buyItem.setGoodsPrice(cursor.getDouble(cursor.getColumnIndex("goods_price")));
                buyItem.setQuantity(cursor.getInt(cursor.getColumnIndex("quantity")));
                // 获取图片数据
                byte[] imageBytes = cursor.getBlob(cursor.getColumnIndex("image"));
                // 将字节数据转换为Bitmap（这里需要在适配器中处理）
                buyItem.setImageBytes(imageBytes);
                buyItems.add(buyItem);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return buyItems.stream().filter(buyItem::hasImage).collect(Collectors.toList());
    }

    @SuppressLint("Range")
    public void removeFromBuyByGoodsId(int goodsId) {
        // 查询 buy 表，找到对应的 goodsId 的 _id
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT _id FROM " + DBHelper.buyTable.NAME + " WHERE " + DBHelper.buyTable.GOODS_ID + " = ?", new String[]{String.valueOf(goodsId)});

        int buyItemId = -1; // 默认值，表示未找到
        if (cursor.moveToFirst()) {
            buyItemId = cursor.getInt(cursor.getColumnIndex(DBHelper.buyTable._ID));
        }
        cursor.close();
        db.close();

        // 如果找到了对应的 buyItemId，执行删除操作
        if (buyItemId != -1) {
            dbHelper.removeFromCart2(buyItemId);
        }
    }
    // 辅助方法，获取当前登录用户的ID
    private int getUserId() {
        return mSpUtils.getInt(SpUtils.LOGIN_KEY, -1); // 使用spUtils而不是new SpUtils(this)
    }
}
